"""
Diagnose AIPPT API Connection Issues
Tests network connectivity and API accessibility
"""
import os
import sys
import time
import socket
import requests
from urllib.parse import urlparse

# Add project root to path
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, project_root)

# Load environment variables
from dotenv import load_dotenv
env_path = os.path.join(project_root, '.env')
load_dotenv(env_path)


def test_dns_resolution(hostname: str) -> bool:
    """Test DNS resolution"""
    print(f"\n1. Testing DNS resolution for {hostname}...")
    try:
        ip = socket.gethostbyname(hostname)
        print(f"   SUCCESS: Resolved to {ip}")
        return True
    except socket.gaierror as e:
        print(f"   FAILED: {e}")
        return False


def test_tcp_connection(hostname: str, port: int = 443) -> bool:
    """Test TCP connection"""
    print(f"\n2. Testing TCP connection to {hostname}:{port}...")
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(5)
        result = sock.connect_ex((hostname, port))
        sock.close()

        if result == 0:
            print(f"   SUCCESS: Port {port} is open")
            return True
        else:
            print(f"   FAILED: Port {port} is closed or filtered")
            return False
    except Exception as e:
        print(f"   FAILED: {e}")
        return False


def test_http_request(url: str, timeout: int = 10) -> dict:
    """Test HTTP request with various timeouts"""
    print(f"\n3. Testing HTTP request to {url}...")
    print(f"   Timeout: {timeout}s")

    start_time = time.time()
    try:
        response = requests.get(url, timeout=timeout, verify=True)
        elapsed = time.time() - start_time

        print(f"   SUCCESS: Status {response.status_code}")
        print(f"   Response time: {elapsed:.2f}s")
        print(f"   Response size: {len(response.content)} bytes")

        return {
            'success': True,
            'status_code': response.status_code,
            'elapsed': elapsed,
            'content_size': len(response.content)
        }
    except requests.exceptions.Timeout:
        elapsed = time.time() - start_time
        print(f"   FAILED: Request timed out after {elapsed:.2f}s")
        return {'success': False, 'error': 'timeout', 'elapsed': elapsed}
    except requests.exceptions.SSLError as e:
        print(f"   FAILED: SSL Error - {e}")
        return {'success': False, 'error': 'ssl_error', 'details': str(e)}
    except requests.exceptions.ConnectionError as e:
        print(f"   FAILED: Connection Error - {e}")
        return {'success': False, 'error': 'connection_error', 'details': str(e)}
    except Exception as e:
        print(f"   FAILED: {type(e).__name__} - {e}")
        return {'success': False, 'error': type(e).__name__, 'details': str(e)}


def test_api_endpoint(base_url: str, token: str) -> dict:
    """Test actual API endpoint with authentication"""
    print(f"\n4. Testing API endpoint with authentication...")

    # Try a simple endpoint that should respond quickly
    test_url = f"{base_url}/ppt/template/options"

    headers = {
        'token': token,
        'Content-Type': 'application/json'
    }

    start_time = time.time()
    try:
        response = requests.get(test_url, headers=headers, timeout=10)
        elapsed = time.time() - start_time

        print(f"   Status: {response.status_code}")
        print(f"   Response time: {elapsed:.2f}s")

        if response.status_code == 200:
            print(f"   SUCCESS: API is accessible")
            try:
                data = response.json()
                print(f"   Response preview: {str(data)[:200]}")
            except:
                pass
            return {'success': True, 'status_code': 200}
        elif response.status_code == 401:
            print(f"   FAILED: Unauthorized - Token may be invalid")
            return {'success': False, 'error': 'unauthorized'}
        elif response.status_code == 403:
            print(f"   FAILED: Forbidden - Token may lack permissions")
            return {'success': False, 'error': 'forbidden'}
        else:
            print(f"   FAILED: Unexpected status code")
            return {'success': False, 'status_code': response.status_code}

    except requests.exceptions.Timeout:
        elapsed = time.time() - start_time
        print(f"   FAILED: API request timed out after {elapsed:.2f}s")
        return {'success': False, 'error': 'timeout'}
    except Exception as e:
        print(f"   FAILED: {type(e).__name__} - {e}")
        return {'success': False, 'error': type(e).__name__}


def check_proxy_settings():
    """Check if proxy is configured"""
    print(f"\n5. Checking proxy settings...")

    http_proxy = os.getenv('HTTP_PROXY') or os.getenv('http_proxy')
    https_proxy = os.getenv('HTTPS_PROXY') or os.getenv('https_proxy')

    if http_proxy:
        print(f"   HTTP_PROXY: {http_proxy}")
    else:
        print(f"   HTTP_PROXY: Not set")

    if https_proxy:
        print(f"   HTTPS_PROXY: {https_proxy}")
    else:
        print(f"   HTTPS_PROXY: Not set")


def main():
    print("=" * 60)
    print("AIPPT API Connection Diagnostics")
    print("=" * 60)

    # Get configuration
    base_url = os.getenv('AIPPT_BASE_URL', 'https://docmee.cn/api')
    token = os.getenv('AIPPT_TOKEN', '')

    print(f"\nConfiguration:")
    print(f"  Base URL: {base_url}")
    print(f"  Token: {token[:10]}... (length: {len(token)})")

    # Parse hostname
    parsed = urlparse(base_url)
    hostname = parsed.hostname or 'docmee.cn'

    # Run diagnostics
    results = {}

    # Test 1: DNS
    results['dns'] = test_dns_resolution(hostname)

    # Test 2: TCP
    results['tcp'] = test_tcp_connection(hostname, 443)

    # Test 3: Basic HTTP
    results['http'] = test_http_request(f"https://{hostname}", timeout=10)

    # Test 4: API endpoint
    if token:
        results['api'] = test_api_endpoint(base_url, token)
    else:
        print(f"\n4. Skipping API test (no token configured)")
        results['api'] = {'success': False, 'error': 'no_token'}

    # Test 5: Proxy
    check_proxy_settings()

    # Summary
    print("\n" + "=" * 60)
    print("DIAGNOSTIC SUMMARY")
    print("=" * 60)

    all_tests = [
        ('DNS Resolution', results.get('dns', False)),
        ('TCP Connection', results.get('tcp', False)),
        ('HTTP Request', results.get('http', {}).get('success', False)),
        ('API Endpoint', results.get('api', {}).get('success', False))
    ]

    for test_name, passed in all_tests:
        status = "PASSED" if passed else "FAILED"
        print(f"{test_name:20} {status}")

    print("=" * 60)

    # Recommendations
    print("\nRECOMMENDATIONS:")

    if not results.get('dns'):
        print("- DNS resolution failed. Check your network connection.")
        print("- Try using a VPN or different DNS server.")

    if not results.get('tcp'):
        print("- TCP connection failed. Firewall may be blocking HTTPS.")
        print("- Check firewall settings or try from a different network.")

    if results.get('http', {}).get('error') == 'timeout':
        print("- HTTP requests are timing out.")
        print("- Network may be slow or unstable.")
        print("- Consider increasing timeout values.")

    if results.get('api', {}).get('error') == 'unauthorized':
        print("- API authentication failed.")
        print("- Verify AIPPT_TOKEN is correct and not expired.")

    if results.get('api', {}).get('error') == 'timeout':
        print("- API endpoint is timing out but basic HTTP works.")
        print("- The API server may be experiencing issues.")
        print("- Try again later or contact API support.")

    print("\n")


if __name__ == '__main__':
    main()
